package com.yougou.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.yougou.App;

public class SPUtils {
    
    private static final String SP_NAME = "yougou_prefs";
    private static SharedPreferences sp;
    private static Gson gson = new Gson();
    
    private static SharedPreferences getSP() {
        if (sp == null) {
            sp = App.getContext().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        }
        return sp;
    }
    
    public static void putString(String key, String value) {
        getSP().edit().putString(key, value).apply();
    }
    
    public static String getString(String key) {
        return getSP().getString(key, "");
    }
    
    public static String getString(String key, String defaultValue) {
        return getSP().getString(key, defaultValue);
    }
    
    public static void putInt(String key, int value) {
        getSP().edit().putInt(key, value).apply();
    }
    
    public static int getInt(String key) {
        return getSP().getInt(key, 0);
    }
    
    public static int getInt(String key, int defaultValue) {
        return getSP().getInt(key, defaultValue);
    }
    
    public static void putBoolean(String key, boolean value) {
        getSP().edit().putBoolean(key, value).apply();
    }
    
    public static boolean getBoolean(String key) {
        return getSP().getBoolean(key, false);
    }
    
    public static boolean getBoolean(String key, boolean defaultValue) {
        return getSP().getBoolean(key, defaultValue);
    }
    
    public static void putLong(String key, long value) {
        getSP().edit().putLong(key, value).apply();
    }
    
    public static long getLong(String key) {
        return getSP().getLong(key, 0L);
    }
    
    public static long getLong(String key, long defaultValue) {
        return getSP().getLong(key, defaultValue);
    }
    
    
    public static <T> void putObject(String key, T object) {
        String json = gson.toJson(object);
        putString(key, json);
    }
    
    
    public static <T> T getObject(String key, Class<T> clazz) {
        String json = getString(key);
        if (json == null || json.isEmpty()) {
            return null;
        }
        try {
            return gson.fromJson(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    
    public static void remove(String key) {
        getSP().edit().remove(key).apply();
    }
    
    
    public static void clear() {
        getSP().edit().clear().apply();
    }
    
    
    public static boolean contains(String key) {
        return getSP().contains(key);
    }
}

